﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using DH.Web.Controllers;
using DH.Entity;
using DH.Service.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using DH.Service.Domain.User;
using DH.Service.Domain.Role;
using Microsoft.Extensions.Logging;
using NLog;
using Microsoft.AspNetCore.Authorization;
using DH.Web.Filter;
using DH.Core;
using DH.Web.MVC.Extensions;
using DH.Web.Attributes;
using System.ComponentModel;
using Newtonsoft.Json;
using DH.Service.Domain;
using DH.Core.Helper;

namespace DH.Web.MVC.Controllers
{
    [Authorize]
    [Route("Role")]
    [Resource("角色(资源)")]
    [Guid("670521e6-01ab-462b-9977-cf85c20eaf26")]
    public class RoleController : SiteController<RoleEntity, RoleViewModel, string>
    {
        protected RoleService _roleService;
        protected PrivilegeService _privilegeService;
        protected MenuService _menuService;
        protected UserService _userService;
        protected OrganizeService _organizeService;
        //protected IServiceCollection _service;
        //protected Microsoft.Extensions.Logging.ILogger _log;
        static Logger Logger = LogManager.GetCurrentClassLogger();
        public RoleController(IServiceCollection serviceCollection,
                              RoleService roleService) : base(serviceCollection, roleService)
        {
            _roleService = roleService;
            //_service = serviceCollection;

            _privilegeService = _service.BuildServiceProvider().GetService<PrivilegeService> ();
            _menuService = _service.BuildServiceProvider().GetService<MenuService>();
            _userService = _service.BuildServiceProvider().GetService<UserService>();
            _organizeService = _service.BuildServiceProvider().GetService<OrganizeService>();
            //var logfac = _service.BuildServiceProvider().GetService<ILoggerFactory>();
            //var log = logfac.CreateLogger<OrganizeController>();
            //_log = log;
        }

        [HttpGet]
        [Route("Index")]
        [UIView("角色管理首页")]
        [Guid("f810c752-ae14-4fff-bfaa-4a788b1f84cb")]
        public IActionResult Index()
        {
            ViewBag.CurrentUser = CurrentUserEx;
            ViewBag.CurrentViewId = "f810c752-ae14-4fff-bfaa-4a788b1f84cb";
            return View();
        }

        [HttpGet]
        [Route("Roles")]
        [Function("获取角色列表")]
        [Guid("b72777e1-e9aa-4dfc-aba3-3be74b55bdd8")]
        public IActionResult GetRoleList()
        {
            PagedData<RoleViewModel> models;
            var pagination = GetPagination();
            var queryKey = Request.Query["queryKey"][0];

            var filterObj = new RoleQueryDto();
            var filter = Request.Query["filter"];
            if (filter.Any())
            {
                if (filter[0] != "")
                {
                    filterObj = JsonConvert.DeserializeObject<RoleQueryDto>(filter[0]);
                }

            }

            var res = _roleService.GetList(queryKey,filterObj, pagination);
            models = res.ToViewModelPageData<RoleEntity, RoleViewModel>();
            foreach (var md in models.DataList) {
                md.RoleRangeName = _organizeService.GetOrgNameById(md.RoleRange);
            }

            var result = new { total = models.TotalCount, rows = models.DataList };
            return Json(result);
        }

        [HttpPost]
        [Route("Add")]
        [UserPermissionFilter]
        [Function("添加/编辑角色",isManage:true)]
        [Guid("a6265757-0cf8-4692-ae2d-cb75b6708055")]
        ///<summary>
        ///添加编辑角色
        ///受系统托管
        ///</summary>
        public IActionResult AddRole(RoleViewModel input)
        {
            if (!ModelState.IsValid) {
                return ErrorMessage("实体类验证失败");
            }
            try
            {
                if (!string.IsNullOrWhiteSpace(input.Id)) {
                    input.UpdatedBy = CurrentUser.UserId;
                    input.UpdatedOn = DateTimeOffset.Now;

                    _roleService.Edit(input);
                }
                else {
                    input.UpdatedBy = CurrentUser.UserId;
                    input.CreatedBy = CurrentUser.UserId;
                    _roleService.Add(input);
                }

                return SuccessMessage("执行成功");
            }
            catch (Exception ex) {
                Logger.Error("新增角色发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading {0}", nameof(RoleViewModel));
            }

        }

        [UserPermissionFilter]
        [HttpPost]
        [Route("Delete")]
        [Function("删除角色",isManage:true)]
        [Guid("20742e51-7cc8-4048-8b13-1a75c875ca74")]
        ///<summary>
        ///删除
        ///受系统托管
        ///</summary>
        public IActionResult Delete(string[] ids) {
            try
            {
                //删除角色
                _roleService.Delete(ids);

                ///todo:删除角色后，删除角色权限，角色菜单，角色用户
                //删除角色权限
                //删除角色菜单
                //删除角色用户
                _privilegeService.DeleteRolePrivilege(ids);

                //_roleService.DeleteCascade(ids);


                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("删除角色发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while loading {0}", ids);
            }
        }


        [HttpPost]
        [Route("EnableRole")]
        [Function("启用角色",isManage:true)]
        [Description("启用角色")]
        [Guid("6aec648f-1ed1-4a99-a7bd-c0e7e14f320d")]
        public IActionResult EnableRole(string id)
        {
            try
            {
                _roleService.EnabledRole(id);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("启用角色时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while enable role with id: {0}", id);
            }
        }

        [HttpPost]
        [Route("DisAbleRole")]
        [Function("禁用角色",isManage:true)]
        [Description("禁用角色")]
        [Guid("8e565884-8d9b-4cd8-9467-541786aca47c")]
        public IActionResult DisAbleRole(string id)
        {
            try
            {
                _roleService.DisabledRole(id);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("禁用角色时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while disabling role with id: {0}", id);
            }
        }

        [HttpGet]
        [Route("GetRolePrivilege")]
        [Function("获取角色权限",isManage:false)]
        [Description("获取角色权限")]
        [Guid("37969781-865a-4467-b093-c90512ce68a1")]
        public IActionResult GetRolePrivilege(string roleId,string resourceId)
        {
            var res = _privilegeService.GetRolePrivilge(roleId, resourceId, PrivilegeTypeEnum.Role.ToString(),PrivilegeTypeEnum.Function.ToString());

            return new JsonResult(res);
        }

        [HttpPost]
        [Route("SaveRolePrivilege")]
        [Function("存储角色权限",isManage:true)]
        [Description("存储当前角色权限")]
        [Guid("c8718e8a-9e30-4004-a288-87ba792d8e0e")]
        public IActionResult SaveRolePrivilege(List<RoleFuncsDto> viewModels)
        {
            try
            {
                _privilegeService.Add(viewModels,
                                      CurrentUser.UserId, 
                                      PrivilegeTypeEnum.Role.ToString(),
                                      PrivilegeTypeEnum.Function.ToString(),
                                      true);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("存储角色权限时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while saving role privilege with type : {0}", typeof(List<PrivilegeViewModel>));
            }

            
        }


        /// <summary>
        /// 删除角色权限
        /// 包括：角色功能权限，角色菜单权限，角色用户
        /// </summary>
        /// <param name="role"></param>
        /// <returns></returns>
        public IActionResult DeleteRolePrivilege(string[] ids)
        {
            return null;
        }

        
        [Route("ManageRolePrivilege")]
        [Function("管理角色权限", isManage: true)]
        [Description("管理角色权限弹窗")]
        [Guid("9a113dd3-c517-4b6a-b533-82538ff24066")]
        public IActionResult MangeRolePrivilege()
        {
            return null;
        }

        
        [Route("ManageRolePrivilege")]
        [Function("管理角色菜单", isManage: true)]
        [Description("管理角色菜单弹窗")]
        [Guid("48f3ac2f-0d97-42ad-878b-c46e3960f251")]
        public IActionResult ManageRoleMenus()
        {
            return null;
        }

        
        [Route("ManageRolePrivilege")]
        [Function("管理角色用户", isManage: true)]
        [Description("管理角色用户弹窗")]
        [Guid("7f568dc3-8cb1-4211-bf67-3b57f491c696")]
        public IActionResult ManageRoleUsers()
        {
            return null;
        }

        [HttpPost]
        [Route("SaveRoleMenus")]
        [Function("保存给角色分配的菜单",isManage:true)]
        [Description("保存给角色分配的菜单")]
        [Guid("ea8064b4-bcfb-49dc-ba10-92b412e7c17d")]
        public IActionResult SaveRoleMenus(List<RoleFuncsDto> viewModels) {

            try
            {
                _privilegeService.Add(viewModels,
                                      CurrentUser.UserId,
                                      PrivilegeTypeEnum.Role.ToString(),
                                      PrivilegeTypeEnum.Menu.ToString(),
                                      false);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("存储角色菜单时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while saving role menus with type : {0}", typeof(List<RoleFuncsDto>));
            }
            
        }

        [HttpGet]
        [Route("GetRoleMenus")]
        [Function("获取给角色分配的菜单")]
        [Description("获取给角色分配的菜单")]
        [Guid("8743951e-5049-4eb3-91fc-2bcf0f239057")]
        public IActionResult GetRoleMenus(string roleId) {

            //菜单id集合
            var ids = new List<string>();
            var res = _privilegeService.GetRolePrivilge(roleId, "", PrivilegeTypeEnum.Role.ToString(),PrivilegeTypeEnum.Menu.ToString());

            var parentMenuIds=_menuService.GetByQuery(c => c.Status == true && c.ParentId == "00000000-0000-0000-0000-000000000000").Select(c=>c.Id);

            res = res.Where(c => !parentMenuIds.Contains(c.ObjectId)).ToList();

            return new JsonResult(res);
        }

        [HttpGet]
        [Route("GetRoleUsers")]
        [Function("获取所属角色的用户")]
        [Description("获取所属角色的用户")]
        [Guid("76e4cca1-1d11-41a2-87e4-a639d35bd2c9")]
        public IActionResult GetRoleUsers(string roleId) {

            var res = _privilegeService.GetRolePrivilge(roleId, "", PrivilegeTypeEnum.Role.ToString(), PrivilegeTypeEnum.User.ToString()).Select(c=>c.ObjectId);

            if (res.Any())
            {
                var users = _userService.GetByQuery(c => c.DH_EnableMark == true && c.DH_DeleteMark == false && res.Contains(c.Id));

                var usersSimpleInfo = users.Select(c => new
                {
                    c.Id,
                    c.DH_Account,
                    c.DH_NickName
                });

                return new JsonResult(usersSimpleInfo);
            }
            else {
                return new JsonResult(new List<object>() { });
            }

            
        }


        [HttpPost]
        [Route("SaveRoleUsers")]
        [Function("保存所属角色的用户",isManage:true)]
        [Description("保存所属角色的用户")]
        [Guid("cb616a20-d83e-4952-af2f-47b259307299")]
        public IActionResult SaveRoleUsers(List<RoleFuncsDto> viewModels)
        {
            try
            {
                _privilegeService.Add(viewModels,
                                      CurrentUser.UserId,
                                      PrivilegeTypeEnum.Role.ToString(),
                                      PrivilegeTypeEnum.User.ToString(),
                                      false);
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("存储角色用户时发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while saving role users with type : {0}", typeof(List<RoleFuncsDto>));
            }
        }

        [HttpPost]
        [Route("DeleteRoleUsers")]
        [Function("删除角色用户",isManage:true)]
        [Description("删除角色用户")]
        [Guid("ed1a4b12-a450-4230-8c31-b14156cfecfe")]
        public IActionResult DeleteRoleUsers(string roleId,string[] userids) {
            try
            {
                //删除角色用户
                _privilegeService.DeleteRoleUsers(roleId,userids);
               
                return SuccessMessage("执行成功");
            }
            catch (Exception ex)
            {
                Logger.Error("删除角色用户发生异常：" + ex.Message);
                return InternalServerError(ex, "Error while delete role users :{0}", userids);
            }

        }


    }
}